<template>
  <div class="user-appointments">
    <el-form-item label="科室:" class="form-item" style="width: 50vw">
      <el-select v-model="role" placeholder="请选择预约科室">
        <el-option
          v-for="option in roles"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="日期:" class="form-item small-item">
      <el-date-picker
        v-model="date"
        type="date"
        placeholder="选择日期"
        style="width: 100%"
      ></el-date-picker>
    </el-form-item>
    <el-form-item label="时间:" class="form-item small-item">
      <el-time-picker
        v-model="time"
        :disabled-hours="disabledHours"
        :disabled-minutes="disabledMinutes"
        placeholder="任意时间点"
        format="HH:mm"
      />
    </el-form-item>
    <el-form-item label="医生：" class="form-item">
      <el-table :data="DoctorData" height="300" style="width: 100%">
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="left_nums" label="剩余名额" width="100" />
        <el-table-column prop="appointment" label="预约" width="100">
          <template v-slot="scope">
            <el-button
              type="primary"
              size="mini"
              :disabled="!date || !time || !role"
              @click="handleYu(scope.row)"
              >预约</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-button
      type="success"
      style="width: 100px"
      bg
      :disabled="!role"
      @click="handleGua()"
      >直接挂号</el-button
    >
  </div>
</template>

<script>
import axios from "axios";
import dayjs from "dayjs";
import { ElNotification } from "element-plus";
export default {
  name: "UserAppointment",
  data() {
    return {
      role: "", // 绑定选择框的值
      id: "",
      roles: [
        { label: "内科", value: "internal" },
        { label: "外科", value: "surgery" },
        // 可以在这里添加更多的选项
      ],
      date: new Date(), // 绑定日期选择器的值
      time: new Date(), // 绑定时间选择器的值
      DoctorData: [
        {
          name: "张三",
          department: "内科",
          left_nums: 10,
        },
        {
          name: "李四",
          department: "外科",
          left_nums: 5,
        },
      ],
    };
  },
  methods: {
    handleGua() {
      axios
        .post("http://192.168.228.82:8080/arrange/add", null, {
          params: {
            pId: this.id,
            arrangeTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
            department: this.roles[this.role - 1].label,
          },
        })
        .then((res) => {
          console.log("直接挂号成功！");
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          ElNotification({
            message: `您已经成功挂号，挂号医生为 ${res.data.doctor.name},请去缴费！`,
            type: "success",
            position: "top-left",
            plain: true,
            offset: 250,
            duration: 1000,
          });
        });
    },
    handleYu(row) {
      console.log("预约");
      console.log("选择的科室:", this.roles[this.role - 1].label);
      console.log("选择的日期:", this.formatDate());
      console.log("选择的医生:", row);
      axios
        .get("http://192.168.228.82:8080/patient/addArrange", {
          params: {
            time: this.formatDate(),
            pid: this.id,
            did: row.did,
          },
        })
        .then(() => {
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          ElNotification({
            message: `您已经成功挂号，挂号医生为 ${row.name},请去缴费！`,
            type: "success",
            position: "top-left",
            plain: true,
            offset: 250,
            duration: 1000,
          });
        });
    },
    disabledHours() {
      const hours = [];
      console.log(this.date.getDate(), new Date().getDate());
      for (let i = 0; i < 24; i++) {
        if (i < 8 || i > 20) {
          hours.push(i);
        } else if (this.date.getDate() === new Date().getDate()) {
          if (i < new Date().getHours()) {
            hours.push(i);
          }
        }
      }
      return hours;
    },
    disabledMinutes(hour) {
      if (
        this.date.getDate() === new Date().getDate() &&
        hour == new Date().getHours()
      ) {
        let minutes = [];
        for (let i = 0; i < new Date().getMinutes(); i++) {
          minutes.push(i);
        }
        return minutes;
      }
      return [];
    },
    formatDate() {
      const d = new Date(this.date);
      const t = new Date(this.time);
      const year = d.getFullYear();
      const month = `0${d.getMonth() + 1}`.slice(-2);
      const day = `0${d.getDate()}`.slice(-2);
      const hours = `0${t.getHours()}`.slice(-2);
      const minutes = `0${t.getMinutes()}`.slice(-2);
      const seconds = `0${t.getSeconds()}`.slice(-2);
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    async fetchDoctorDataByDepartment(department) {
      try {
        const response = await axios.get(
          "http://192.168.228.82:8080/doctor/getDoctorsWithAvailableSlots/ByDepartment",
          {
            params: {
              arrangeTime: this.formatDate(),
              department: department,
            },
          }
        );
        console.log(response.data);
        this.DoctorData = response.data.map((item) => ({
          name: item.name,
          department: item.department,
          left_nums: item.remainingSlots,
          did: item.did,
        }));
      } catch (error) {
        console.error("获取医生数据失败:", error);
      }
    },
  },
  async mounted() {
    this.id = JSON.parse(localStorage.getItem("user")).pid;
    try {
      axios
        .get("http://192.168.228.82:8080/patient/getDepartment")
        .then((res) => {
          this.roles = res.data.map((item, index) => ({
            label: item,
            value: index + 1,
          }));
        })
        .then(() => {
          console.log("获取科室数据成功:", this.roles);
          axios
            .get(
              "http://192.168.228.82:8080/doctor/getDoctorsWithAvailableSlots",
              {
                params: {
                  arrangeTime: this.formatDate(),
                },
              }
            )
            .then((res) => {
              console.log(res);
              this.DoctorData = res.data.map((item) => ({
                name: item.name,
                department: item.department,
                left_nums: item.remainingSlots,
              }));
            });
        });
    } catch (error) {
      console.error("获取数据失败:", error);
    }
  },
  watch: {
    role(newRole) {
      if (newRole) {
        console.log("选择的科室:", newRole);
        this.role = newRole;
        this.fetchDoctorDataByDepartment(this.roles[newRole - 1].label);
      }
    },
    date(newDate) {
      if (newDate) {
        console.log("选择的日期:", this.formatDate());
        this.fetchDoctorDataByDepartment(this.roles[this.role].label);
      }
    },
    time(newTime) {
      if (newTime) {
        console.log("选择的时间:", this.formatDate());
        this.fetchDoctorDataByDepartment(this.roles[this.role].label);
      }
    },
  },
};
</script>
<style scoped>
.user-appointments {
  margin-top: 55px;
}
</style>
